package com.pwc.conversionTool.biz.sendSoap;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.pwc.conversionTool.biz.TaskBiz;
import com.pwc.conversionTool.dao.LogDao;
import com.pwc.conversionTool.entity.Task;
import com.pwc.conversionTool.entity.TaskFlow;
import com.pwc.conversionTool.entity.TaskFlowLog;
import com.pwc.conversionTool.entity.TaskFlowRunningType;

public class TaskFlowProcess {
	
	
	private TaskFlow taskFlow;

	private List<Task> tasks;
	
	private TaskFlowLog log;
	
	private TaskBiz taskBiz = new TaskBiz();
	private LogDao logDao=new LogDao();
	
	private TaskProcess taskProcess=new TaskProcess();

	public TaskFlowProcess(TaskFlow taskFlow) {
		super();
		
		try {
			this.log = new TaskFlowLog(taskFlow.getTaskFlowName(),taskFlow.getKey());
			this.taskFlow = taskFlow;
			this.tasks = taskBiz.getTasksByTaskFlowId(taskFlow.getId());
			log.addMessage(" initial taskflow process success");
		} catch (Exception e) {
			log.addMessage(" error in initial taskflow process ");
			log.addMessage(e.getMessage());
			log.addMessage(Arrays.toString(e.getStackTrace()));
			e.printStackTrace();
		}
		
	}
	
	
	
	public boolean runWorkFlow() {
		
		taskFlow.setStatus(TaskFlowRunningType.RUNNING);
		
		taskBiz.saveTaskFlow(taskFlow);
		
		try {

			for (Task task : tasks) {
				log.addMessage(task.getTaskName()+" is running.");
				taskProcess.initial(task);
				boolean result=taskProcess.doSendProcess();
				if(!result)
				{					
					log.setHasError(true);
					log.addMessage(task.getTaskName()+" has error.");
					break;
				}else {
					log.addMessage(task.getTaskName()+" is completed.");
				}
			}

		} catch (Exception e) {
			log.addMessage("system error in run task process loop");
			log.addMessage(e.getMessage());
			log.addMessage(Arrays.toString(e.getStackTrace()));
			log.setHasError(true);
			e.printStackTrace();
			taskFlow.setStatus(TaskFlowRunningType.ERROR);
		} 
		
		
		if(log.isHasError())
		{
			taskFlow.setStatus(TaskFlowRunningType.ERROR);
		}else {
			taskFlow.setStatus(TaskFlowRunningType.COMPLETE);
		}
		
		
		taskFlow.setComplateDate(new Date());
		
		taskBiz.saveTaskFlow(taskFlow);
		
		return !log.isHasError();
	}
	
	

}
